<?php

class Clubs extends MY_SecuredController {

	function Clubs() {
		parent::MY_SecuredController();

		$this->requireRole('Admin');

		$this->load->helper(array('form','url'));
		$this->load->library('form_validation');
		$this->load->library('formdate');
	}

	function index() {
		$this->_preRender(Current_User::user()->id);

		if ($this->isOwner)
		  $data['clubs'] = Doctrine::getTable('ClubModel')->findAll();
		else
		  $data['clubs'] = ClubModel::findAllForAdmin(Current_User::user()->id);

		$this->render('admin/clubs/index', $data);
	}

	function see($id) {
		$this->_preRender(Current_User::user()->id);
		$this->_checkClubAdmin($id);

		$data['club'] = ClubModel::getClub($id);
		$data['selected'] = $id;

		if (!$data['club']) {
			$this->redirect('admin/clubs/index', array(
                    'message' => 'Ooops, that club could not be found - choose another one.',
			), true);
		}

		if ($this->isOwner)
          $data['clubs'] = Doctrine::getTable('ClubModel')->findAll();
        else
          $data['clubs'] = ClubModel::findAllForAdmin(Current_User::user()->id);

		$this->render('admin/clubs/view', $data);
	}


	function ajax($op, $clubid) {
		if ($op == 'view') {
			$club = ClubModel::getClub($clubid)->toArray();

			echo json_encode($club);
		}
	}

	function add() {
		$this->requireRole('Owner');
		$this->_preRender(Current_User::user()->id);

		if (!$this->input->post('action')) {

			$data['club'] = new ClubModel();
			$this->render('admin/clubs/add', $data);
		}
		else {
			if ($this->_submit_validate() === FALSE) {
				$data['club'] = new ClubModel();
				$this->render('admin/clubs/add', $data, $this->error(validation_errors('<li>','<li>')));
				return;
			}

			$c = new ClubModel();
			$c->merge($_POST);

			try {
				$c->save();
			}
			catch (Exception $e) {
				$this->render('admin/clubs/index', $data, $this->error(array(
	                'message' => 'Ooops, the club could not be added - please try again later.',
	                'exception' => $e
				)));
				return;
			}

			$this->redirect('admin/clubs/index','Club added successfully!');
		}
	}
	
	function add_ajax($clubid, $type, $civlid) {
		$club = ClubModel::getClub($clubid);
		$user = PersonModel::getPerson($civlid);

		$data['club'] = $data;

		if (!isset($club) || !isset($user)) {
			return;  // watta?
		}

		$save = false;

		if ($type == 'admin') {
			if (!$club->isAdmin($civlid)) { // check if the user is already an admin
				$club->Admins[] = $user;
				$save = true;
			}
		}
		else if ($type == 'contact') {
			if (!$club->isContact($civlid)) { // check if the user is already an admin
				$club->Contacts[] = $user;
				$save = true;
			}
		}
		else if ($type == 'authority') {
			if (!$club->isAuthority($civlid)) { // check if the user is already an admin
				$club->Authorities[] = $user;
				$save = true;
			}
		}

		if ($save) {
			try {
				$club->save();
			}
			catch (Exception $e) {
				$this->render('admin/clubs/edit/'.$clubid, $data, $this->error(array(
                    'message' => 'Ooops, the Person could not be added - please try again later.',
                    'exception' => $e
				)));
				return;
			}

			$this->redirect('admin/clubs/edit/'.$clubid,'Person added successfully!');
		}
		$this->redirect('admin/clubs/edit/'.$clubid);
	}

	function edit($id) {
		$this->_preRender(Current_User::user()->id);
        $this->_checkClubAdmin($id);
		
		$data['clubs'] = Doctrine::getTable('ClubModel')->findAll();
		
		if (!$this->input->post('action')) {
			$this->_preRender(Current_User::user()->id);

			$data['club'] = ClubModel::getClub($id);

			$this->render('admin/clubs/edit', $data);
		}
		else {
			$club = ClubModel::getClub($id);

			if (!$club) {
				$this->render('admin/clubs/index',$data, $this->error(array(
                    'message' => 'Ooops, the club could not be found, operation has been cancelled!',
				)));
				return;
			}

			$club->merge($_POST);

			try {
				$club->save();
			}
			catch (Exception $e) {
				$this->render('admin/clubs/index', $data, $this->error(array(
                    'message' => 'Ooops, the information could not be updated, please try again later.',
                    'exception' => $e
				)));
				return;
			}

			$this->redirect('admin/clubs/index', 'Club has been successfully updated!');
		}
	}

	function delete($id) {
        $this->requireRole('Owner');
		$this->_preRender(Current_User::user()->id);
		
		$data['clubs'] = Doctrine::getTable('ClubModel')->findAll();

		$club = ClubModel::getClub($id);

		if (!$club) {
			$this->redirect('admin/clubs/index', array(
                    'message' => 'Ooops, the club could not be found, operation has been cancelled!',
			));
			return;
		}

		try {
			$club->delete();
		}
		catch (Exception $e) {
			$this->redirect('admin/clubs/index', array(
                    'message' => 'Ooops, the club could not be deleted, please try again later.',
                    'exception' => $e
			), true);

			return;
		}

		$this->redirect('admin/clubs/index', 'Club has been successfully deleted!');
	}

	function delete_person($clubid, $type, $civlid) {
		if ($type == 'contact') {
			if ($club->isContact($civlid)) { // check if the user is already an admin
				$index = 0;
				$found = false;
				foreach ($club->ClubContactModel as $e) {
					if ($e->person_id == $civlid) {
						$found = true;
						break;
					}
					$index++;
				}
					
				if ($found) {
					try {
						$club->ClubContactModel[$index]->delete();
					}
					catch (Exception $e) {
						$this->redirect('admin/clubs/edit/'.$clubid, array(
                            'message' => 'Ooops, the Contact could not be deleted - please try again later.',
                            'exception' => $e), true);
						return;
					}

					$this->redirect('admin/clubs/edit/'.$clubid,'Contact deleted successfully!');
				}
			}
		}
		else if ($type == 'authority') {
			if ($club->isAuthority($civlid)) { // check if the user is already an admin
				$index = 0;
				$found = false;
				foreach ($club->ClubAuthorityModel as $e) {
					if ($e->person_id == $civlid) {
						$found = true;
						break;
					}
					$index++;
				}
					
				if ($found) {
					try {
						$club->ClubAuthorityModel[$index]->delete();
					}
					catch (Exception $e) {
						$this->redirect('admin/clubs/edit/'.$clubid, array(
                            'message' => 'Ooops, the Authority could not be deleted - please try again later.',
                            'exception' => $e), true);
						return;
					}

					$this->redirect('admin/clubs/edit/'.$clubid,'Authority deleted successfully!');
				}
			}
		}

		$this->redirect('admin/clubs/edit/'.$clubid);
	}

	public function admins($op, $clubid, $civlid = null) {
		$this->_preRender(Current_User::user()->id);
		$this->_checkClubAdmin($clubid);

		$club = ClubModel::getClub($clubid);
		if ($club === false) {
			$this->redirect('admin/clubs','Could not find club with ID '.$clubid, true);
			return;
		}

		$data['club'] = $club;

		try {
			if ($op == 'add') {
				$club->addAdmin($this->input->post('admin_id'));
			}
			else if ($op == 'delete') {
				$club->deleteAdmin($civlid);
			}
			else if ($op == 'search') {
				$results = PersonModel::locatePerson($this->input->post('admin_term'));
				$options = array();
				$admins = array();
				 
				foreach ($club->Admins as $ca) {
					$admins[] = $ca->id;
				}
				 
				foreach ($results as $k => $a) {
					if (!in_array($a['id'], $admins)) {
						$options[$a['id']] = $a['name'];
					}
				}
				 
				$data['admin_search_results'] = $options;

				$this->render('admin/clubs/edit', $data);
				return;
			}
		}
		catch (Exception $e) {
			$this->redirect('admin/clubs/edit/'.$clubid, array(
                'message' => 'Ooops, the operation '.$op.' could not performed - try again later',
                'exception' => $e), true);
			return;
		}

		$this->redirect('admin/clubs/edit/'.$clubid);
	}

	public function contacts($op, $clubid, $civlid = null) {
		$this->_preRender(Current_User::user()->id);
		$this->_checkClubAdmin($clubid);

		$club = ClubModel::getClub($clubid);
		if ($club === false) {
			$this->redirect('admin/clubs','Could not find club with ID '.$clubid, true);
			return;
		}

		$data['club'] = $club;

		try {
			if ($op == 'add') {
				$club->addContact($this->input->post('contact_id'));
			}
			else if ($op == 'delete') {
				$club->deleteContact($civlid);
			}
			else if ($op == 'search') {
				$results = PersonModel::locatePerson($this->input->post('contact_term'));
				$options = array();
				$contacts = array();

				foreach ($club->Contacts as $ca) {
					$contacts[] = $ca->id;
				}

				foreach ($results as $k => $a) {
					if (!in_array($a['id'], $contacts)) {
						$options[$a['id']] = $a['name'];
					}
				}

				$data['contact_search_results'] = $options;

				$this->render('admin/clubs/edit', $data);
				return;
			}
		}
		catch (Exception $e) {
			$this->redirect('admin/clubs/edit/'.$clubid, array(
                'message' => 'Ooops, the operation '.$op.' could not performed - try again later',
                'exception' => $e), true);
			return;
		}

		$this->redirect('admin/clubs/edit/'.$clubid);
	}
	
	public function authorities($op, $clubid, $civlid = null) {
		$this->_preRender(Current_User::user()->id);
		$this->_checkClubAdmin($clubid);

		$club = ClubModel::getClub($clubid);
		if ($club === false) {
			$this->redirect('admin/clubs','Could not find club with ID '.$clubid, true);
			return;
		}

		$data['club'] = $club;

		try {
			if ($op == 'add') {
				$authid = $this->input->post('authority_id');
				$authpos = $this->input->post('authority_position');
				
				if (!isset($authid) || !isset($authpos)) {
					$this->redirect('admin/clubs','Not enough arguments for operation (add)', true);
					return;
				}
				
				$club->addAuthority($authid, $authpos);
			}
			else if ($op == 'delete') {
				$club->deleteAuthority($civlid);
			}
			else if ($op == 'search') {
				$results = PersonModel::locatePerson($this->input->post('authority_term'));
				$options = array();
				$authorities = array();

				foreach ($club->Authorities as $ca) {
					$authorities[] = $ca->id;
				}

				foreach ($results as $k => $a) {
					if (!in_array($a['id'], $authorities)) {
						$options[$a['id']] = $a['name'];
					}
				}

				$data['authority_search_results'] = $options;

				$this->render('admin/clubs/edit', $data);
				return;
			}
		}
		catch (Exception $e) {
			$this->redirect('admin/clubs/edit/'.$clubid, array(
                'message' => 'Ooops, the operation '.$op.' could not performed - try again later',
                'exception' => $e), true);
			return;
		}

		$this->redirect('admin/clubs/edit/'.$clubid);
	}
	
	private function _checkClubAdmin($clubid) {
		if ($this->isOwner)
		  return true;
		
		$user = Current_User::user();
		$club = ClubModel::getClub($clubid);
		
		if (!$club->isAdmin($user->id)) {
			log_message('debug', 'User '.$user->id.' does not have permissions for club '.$clubid);
			
			$this->redirect('auth/denied', "You don't have enough permissions to access this option!", true);
		}
	}

	private function _submit_validate() {
		$this->form_validation->set_rules('name', 'Name',
			'required|alpha_numeric[Club.name]');

		return $this->form_validation->run();

	}
}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */